{"componentChunkName":"component---src-templates-post-jsx","path":"/[NextStep]11/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"168191bb-b6de-5d4d-9d33-b9b8183f3857","excerpt":"자바 웹 프로그래밍 Next Step - 박재성을 읽고 인용하고 정리하는 POST입니다. 🚩 왜 DI가 필요한가? 먼저 의존관계(dependency)에 대해 생각해보자. 객체에게 의존관계란 무엇이고 어떤 경우에 의존관계가 발생할까? 의존관계\n: 객체 혼자 모든 일을 처리하기 힘들기에 작업을 다른 객체에게 위임하면서 발생한다. 즉, 내가 가진 책임과 역할을…","html":"<p><em>[자바 웹 프로그래밍 Next Step - 박재성]을 읽고 인용하고 정리하는 POST입니다.</em></p>\n<h2>🚩 왜 DI가 필요한가?</h2>\n<p>먼저 의존관계(dependency)에 대해 생각해보자. 객체에게 의존관계란 무엇이고 어떤 경우에 의존관계가 발생할까?</p>\n<p><strong>의존관계</strong><br/>\n: 객체 혼자 모든 일을 처리하기 힘들기에 작업을 다른 객체에게 위임하면서 발생한다.</p>\n<ul>\n<li>즉, <strong>내가 가진 책임과 역할을 다른 객체에게 위임하는 순간 발생</strong>하는 것이다.</li>\n<li>\n<p>예를 들어, <code class=\"language-text\">QnaService</code> 는 질문 삭제 기능 구현을 위해 <code class=\"language-text\">QuestionDao</code> , <code class=\"language-text\">AnswerDao</code> 에게 DB 접근 로직을 위임하고 있다.</p>\n<ul>\n<li>이는 <code class=\"language-text\">QnaService</code> 가 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 에 의존하고 있다는 의미이다.</li>\n</ul>\n</li>\n</ul>\n<p><strong>DI</strong>는 \"객체 간 의존관계를 어떻게 해결하느냐\"에 따른 새로운 접근 방식이다. </p>\n<ul>\n<li>이전까지는 의존관계에 있는 객체를 사용하기 위해 객체를 직접 생성하고, 사용하는 방식으로 구현했다. (<code class=\"language-text\">QnaService</code> 또한 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 사용을 위해 생성하고 사용했다.)</li>\n</ul>\n<p>하지만 이같은 방식으로 구현 시 유연한 개발에 한계가 있기에 <strong>인스턴스를 생성하는 책임</strong>과 <strong>사용하는 책임</strong>을 분리하자는 것이 <strong>DI의 핵심</strong>이다.</p>\n<ul>\n<li>즉 위 예에서 <code class=\"language-text\">QnaService</code> 는 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 에 대한 생성 없이 사용만 함으로써 유연성을 높이자는 방식이다.</li>\n</ul>\n<p>그럼 지금까지의 구현 방식의 문제점을 간단한 예제로 살펴보도록 한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DateMessageProvider {\n    public String getDateMessage() {\n        Calendar now = Calendar.getInstance();\n        int hour = now.get(Calendar.HOUR_OF_DAY);\n\n        if (hour &lt; 12) {\n            return &quot;오전&quot;;\n        }\n        return &quot;오후&quot;;\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>현재 시스템 시간에 따라 오전 또는 오후를 반환하는 클래스이다. 이 클래스의 <code class=\"language-text\">getDateMessage()</code> 에 대한 테스트 클래스는 다음과 같이 구현할 수 있다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DateMessageProviderTest {\n    @Test\n    public void 오전() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오전&quot;, provider.getDateMessage());\n    }\n\n    @Test\n    public void 오후() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오후&quot;, provider.getDateMessage());\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p>위 테스트를 실행하면, 반드시 하나의 테스트는 실패한다. 요구사항은 이 두 테스트가 모두 성공하도록 리팩토링하는 것이다.</p>\n<ul>\n<li>이를 위해서는 먼저 테스트가 모두 성공하지 못하는 원인을 알아야 할 것이다.</li>\n</ul>\n</li>\n</ul>\n<p>원인은, <code class=\"language-text\">DateMessageProvider</code> 가 <code class=\"language-text\">Calendar</code> 와 의존관계를 가지는데 테스트를 위해 <code class=\"language-text\">Calendar</code> 의 시간을 변경할 수 있는 방법이 없다.</p>\n<ul>\n<li>\n<p><strong>소스코드를 컴파일하는 시점에 <code class=\"language-text\">Calendar</code> 인스턴스가 이미 결정</strong>되어 버리기 때문이다.</p>\n<ul>\n<li>이같은 의존관계를 강하게 결합(<strong>tightly coupling</strong>)되어 있다고 한다.</li>\n</ul>\n</li>\n<li>\n<p>모든 테스트의 성공을 위해서는 <strong><code class=\"language-text\">Calendar</code> 에서 반환되는 시간을 변경할 수 있도록 <code class=\"language-text\">DateMessageProvider</code> 를 리팩토링</strong>해야 한다.</p>\n<ul>\n<li>즉, <code class=\"language-text\">getDateMessage()</code> 가 아닌 <code class=\"language-text\">DateMessageProvider</code> 외부에서 <code class=\"language-text\">Calendar</code> 인스턴스 생성 후 전달하는 구조로 바꿔야 한다.</li>\n<li>생성자를 통해 전달하거나, <code class=\"language-text\">getDateMessage()</code> 메소드 인자로 전달할 수 있다. (두번째 방법 사용)</li>\n</ul>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DateMessageProvider {\n    public String getDateMessage(Calendar now) {\n        int hour = now.get(Calendar.HOUR_OF_DAY);\n\n        if (hour &lt; 12) {\n            return &quot;오전&quot;;\n        }\n        return &quot;오후&quot;;\n    }\n}</code>\n        </deckgo-highlight-code>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DateMessageProviderTest {\n    @Test\n    public void 오전() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오전&quot;, provider.getDateMessage(createCurrentDate(11)));\n    }\n\n    @Test\n    public void 오후() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오후&quot;, provider.getDateMessage(createCurrentDate(13)));\n    }\n\n    public Calendar createCurrentDate(int hourOfDay) {\n        Calendar now = Calendar.getInstance();\n        now.set(Calendar.HOUR_OF_DAY, hourOfDay);\n        return now;\n    }\n}</code>\n        </deckgo-highlight-code>\n<p>이제 모든 테스트가 성공이다.</p>\n<ul>\n<li><code class=\"language-text\">DateMessageProvider</code> 가 의존하고 있는 <code class=\"language-text\">Calendar</code> 인스턴스의 생성을 <code class=\"language-text\">DateMessageProvider</code> 가 결정하지 않고, 외부로부터 전달받음으로써 원하는 시간으로 변경해 모든 테스트를 성공할 수 있었다.</li>\n<li>이처럼 DI는 <strong>객체 간의 의존관계에 대한 결정권</strong>을, 의존관계를 가지는 객체(<code class=\"language-text\">DateMessageProvider</code>)가 가지는 것이 아닌 <strong>외부의 누군가가 담당</strong>하도록 맡겨 더 유연한 구조로 개발한다.</li>\n</ul>\n<hr>\n<h2>🚩 DI를 적용하면서 쌓이는 불편함 또는 불만</h2>\n<p>질문/답변 게시판의 <code class=\"language-text\">QnaService</code> 를 DI기반으로 변경하면서 기존의 방식과 어떻게 다르고, 어떤 불편함이 있는지 살펴본다. </p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QnaService {\n    private static QnaService qnaService;\n\n    private QuestionDao questionDao = QuestionDao.getInstance();\n    private AnswerDao answerDao = AnswerDao.getInstance();\n\n    private QnaService() {\n    }\n\n    public static QnaService getInstance() {\n        if (qnaService == null) {\n            qnaService = new QnaService();\n        }\n        return qnaService;\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>보이는 것과 같이 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 에 의존관계를 가진다. 이를 DI구조로 변경해본다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QnaService {\n    private static QnaService qnaService;\n\n    private QuestionDao questionDao;\n    private AnswerDao answerDao;\n\n    private QnaService(QuestionDao questionDao, AnswerDao answerDao) {\n        this.questionDao = questionDao;\n        this.answerDao = answerDao;\n    }\n\n    public static QnaService getInstance(QuestionDao questionDao, AnswerDao answerDao) {\n        if (qnaService == null) {\n            qnaService = new QnaService(questionDao, answerDao);\n        }\n        return qnaService;\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>앞에서 다룬 <code class=\"language-text\">DateMessageProvider</code> 예제에서는 <code class=\"language-text\">getDateMessage()</code> 에서만 발생하는 의존관계를 해결하기 위해 메소드 인자로 전달했다.</li>\n<li>\n<p><code class=\"language-text\">QnaService</code> 의 <code class=\"language-text\">QuestionDao</code> , <code class=\"language-text\">AnswerDao</code> 는 <code class=\"language-text\">QnaService</code> 메소드 전체에서 사용되기에 생성자를 통해 필드로 관리하도록 변경했다.</p>\n<ul>\n<li><code class=\"language-text\">getInstance()</code> 메소드를 변경했기에 이를 사용하는 다른 컨트롤러에서 에러가 발생한다. 이를 <code class=\"language-text\">private QnaService qnaService = QnaService.getInstance(QuestionDao.getInstance(), AnswerDao.getInstance());</code> 와 같이 고쳐준다.</li>\n</ul>\n</li>\n</ul>\n<p>이제 테스트를 수행할텐데, <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 가 DB와의 의존관계를 가지기에 이를 가지지 않도록 변경할 수 있어야 DB에 의존하지 않는 테스트가 가능하다.</p>\n<ul>\n<li>\n<p><code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 를 상속해 메소드를 오버라이딩하여 해결한다.</p>\n<ul>\n<li>먼저 <code class=\"language-text\">MockQuestionDao</code> 클래스를 추가하고 <code class=\"language-text\">QuestionDao</code> 를 상속한다.</li>\n<li>이때, <code class=\"language-text\">QuestionDao</code> 의 기본 생성자가 <strong>싱글톤 패턴의 적용</strong>을 위해 <code class=\"language-text\">private</code> 으로 구현하여 상속할 수 없다.</li>\n</ul>\n</li>\n</ul>\n<p>또 다른 방법으로, 객체 간의 의존관계에 대한 강한 결합(tightly coupling)을 줄이기 위해 DI를 적용하면서 <strong>인터페이스를 사용</strong>한다.</p>\n<ul>\n<li><code class=\"language-text\">QuestionDao</code> → <code class=\"language-text\">JdbcQuestionDao</code> renaming</li>\n<li><code class=\"language-text\">AnswerDao</code> → <code class=\"language-text\">JdbcAnswerDao</code> renaming</li>\n<li>인터페이스 이름을 <code class=\"language-text\">QuestionDao</code> , <code class=\"language-text\">AnswerDao</code> 로 사용</li>\n<li><code class=\"language-text\">JdbcQuestionDao</code> , <code class=\"language-text\">JdbcAnswerDao</code> 에 의존하고 있던 <code class=\"language-text\">QnaService</code> 코드를 새로 추가한 인터페이스 각각에 의존하도록 변경</li>\n<li><code class=\"language-text\">MockQuestionDao</code> , <code class=\"language-text\">MockAnswerDao</code> 를 구현</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class MockAnswerDao implements AnswerDao {\n    private Map&lt;Long, Answer&gt; answers = Maps.newHashMap();\n\n    @Override\n    public Answer insert(Answer answer) {\n        return answers.put(answer.getAnswerId(), answer);\n    }\n\n    @Override\n    public Answer findById(long answerId) {\n        return answers.get(answerId);\n    }\n\n    @Override\n    public List&lt;Answer&gt; findAllByQuestionId(long questionId) {\n        return answers.values().stream()\n                .filter(a -&gt; a.getQuestionId() == questionId)\n                .collect(Collectors.toList());\n    }\n\n    @Override\n    public void delete(Long answerId) {\n        answers.remove(answerId);\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">MockQuestionDao</code> 또한 위와 동일하게 간단한 메모리 DB 역할을 하도록 구현했다.</li>\n<li>이제 테스트 코드를 추가한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QnaServiceTest {\n    private QnaService qnaService;\n    private MockQuestionDao questionDao;\n    private MockAnswerDao answerDao;\n\n    @Before\n    public void setup() {\n        questionDao = new MockQuestionDao();\n        answerDao = new MockAnswerDao();\n        qnaService = QnaService.getInstance(questionDao, answerDao);\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void deleteQuestion_없는_질문() throws Exception {\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void deleteQuestion_다른_사용자() throws Exception {\n        Question question = newQuestion(1L, &quot;javajigi&quot;);\n        questionDao.insert(question);\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n    }\n\n    @Test\n    public void deleteQuestion_같은_사용자_답변없음() throws Exception {\n        Question question = newQuestion(1L, &quot;javajigi&quot;);\n        questionDao.insert(question);\n        qnaService.deleteQuestion(1L, newUser(&quot;javajigi&quot;));\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">newUser</code> 와 <code class=\"language-text\">newQuestion</code> 메소드는 <code class=\"language-text\">model</code> 의 각 클래스 테스트 코드에 구현한다.</li>\n<li>\n<p>위 테스트에서 <code class=\"language-text\">deleteQuestion_같은_사용자_답변없음()</code> 만 \"존재하지 않는 질문입니다.\" 라는 에러가 발생하는 것을 확인할 수 있다. 분명 질문을 추가했는데도 이러한 에러가 뜬다.</p>\n<ul>\n<li>이는 <strong><code class=\"language-text\">QnaService</code> 가 싱글톤 인스턴스</strong>이기에 발생하는 에러이다.</li>\n<li>즉, <code class=\"language-text\">QnaService</code> 가 참조하는 <code class=\"language-text\">QuestionDao</code> (처음 인스턴스 생성 시 해당 인스턴스)와 테스트 메소드에서 생성한 인스턴스가 다르다는 것이다.</li>\n<li>이는 테스트 데이터를 초기화하는 작업을 <code class=\"language-text\">setup()</code> 메소드에서만 하도록 변경해 해결할 수 있다.</li>\n</ul>\n</li>\n</ul>\n<hr>\n<h2>🚩 불만 해소하기</h2>\n<ul>\n<li>싱글톤 패턴을 사용함으로 인해 테스트에 어려움이 있었다. 어떤 형태로든 테스트할 수 있지만 고려해야 할 부분이 많아진다는 것은 반갑지 않다. </li>\n<li>테스트를 위해 매번 <code class=\"language-text\">Mock</code> 객체를 만드는 것은 많은 비용이 드는 작업이다.</li>\n</ul>\n<h3>🔧 싱글톤 패턴을 제거한 DI</h3>\n<p>이 디자인 패턴은 이해하기도 가장 쉽기에 널리 사용되었다. 하지만 그에 따른 단점도 많다. </p>\n<ul>\n<li>싱글톤 패턴으로 구현된 클래스와 의존관계를 가지는 경우 해당 클래스와 강한 의존관계를 가지기 때문에 테스트하기 어렵고,</li>\n<li>생성자를 <code class=\"language-text\">private</code> 로 구현해 상속할 수 없다.</li>\n<li>또한 객체지향 설계 원칙에 따라 개발하는 것을 저해하는 요인이 된다.</li>\n</ul>\n<blockquote>\n<p>싱글톤 패턴을 사용하지 않으면서 인스턴스 하나만 유지하는 방법이 있을까?</p>\n</blockquote>\n<ul>\n<li>지금까지 인스턴스 하나만 생성하기 위해 <code class=\"language-text\">Service</code> , <code class=\"language-text\">DAO</code> , <code class=\"language-text\">JdbcTemplate</code> 은 싱글톤 패턴을 적용했다.</li>\n<li>\n<p>하지만 <strong>컨트롤러</strong>는 이를 적용하지 않고도 같은 효과를 낼 수 있었다.</p>\n<ul>\n<li>서블릿 컨테이너가 <code class=\"language-text\">DispatcherServlet</code> 을 초기화하는 시점에 컨트롤러 인스턴스를 생성한 후 재사용 가능하도록 구현했기 때문이다.</li>\n<li>그렇다면, 이 방식으로 다른 클래스도 인스턴스를 관리한다면 문제를 해결할 수 있지 않을까? 그리고 각 인스턴스 간 의존관계는 DI 기반으로 구현한다.</li>\n</ul>\n</li>\n</ul>\n<p>먼저 <code class=\"language-text\">QnaService</code> 의 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 를 이 방법으로 구현하고 테스트를 진행한다.</p>\n<ul>\n<li>싱글톤 패턴 코드를 제거하고 생성자를 <code class=\"language-text\">public</code> 으로 변경한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QnaService {\n    private QuestionDao questionDao;\n    private AnswerDao answerDao;\n\n    public QnaService(QuestionDao questionDao, AnswerDao answerDao) {\n        this.questionDao = questionDao;\n        this.answerDao = answerDao;\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위와 같이 수정 후 <code class=\"language-text\">getInstance()</code> 메소드를 제거하고 테스트를 진행하면 정상적으로 동작한다. 이제 <code class=\"language-text\">QnaService</code> 와 의존관계를 가지는 다른 컨트롤러들을 수정한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DeleteQuestionController extends AbstractController {\n    private QnaService qnaService;\n    \n    public DeleteQuestionController(QnaService qnaService) {\n        this.qnaService = qnaService;\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위처럼, <code class=\"language-text\">public</code> 생성자를 만들어 인자로 받은 <code class=\"language-text\">QnaService</code> 인스턴스를 사용하도록 수정한다.</li>\n<li>이제 이 컨트롤러들을 생성할 때 <code class=\"language-text\">QnaService</code> 를 DI로 전달해준다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class LegacyHandlerMapping implements HandlerMapping {\n    private static final Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);\n    private Map&lt;String, Controller&gt; mappings = new HashMap&lt;&gt;();\n\n    public void initMapping() {\n        QnaService qnaService = new QnaService(JdbcQuestionDao.getInstance(), JdbcAnswerDao.getInstance());\n        ...\n\n        mappings.put(&quot;/qna/delete&quot;, new DeleteQuestionController(qnaService));\n        mappings.put(&quot;/api/qna/deleteQuestion&quot;, new ApiDeleteQuestionController(qnaService));\n        ...\n\n        logger.info(&quot;Initialized Request Mapping!&quot;);\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p>다시 보니, <code class=\"language-text\">JdbcQuestionDao</code> , <code class=\"language-text\">JdbcAnswerDao</code> 는 아직 싱글톤 패턴을 사용하고 있다. 이들도 싱글톤 패턴을 적용하지 않도록 수정한다. 그리고 연이어 발생하는 컨트롤러에서의 컴파일 에러도 모두 수정한다.</p>\n<ul>\n<li><code class=\"language-text\">getInstance()</code> 메소드를 사용하는 코드를 모두 제거하고, <code class=\"language-text\">public</code> 생성자의 인자로 필요한 인스턴스를 받아 사용하도록 수정하고, 매핑 초기화 시 필요한 인스턴스를 모두 전달해주도록 한다.</li>\n</ul>\n</li>\n</ul>\n<h3>🔧 Mockito를 활용한 테스트</h3>\n<p>DB가 없는 상태에서도 테스트가 가능하도록 <code class=\"language-text\">QuestionDao</code> 와 <code class=\"language-text\">AnswerDao</code> 에 대한 가짜(<code class=\"language-text\">Mock</code>) 클래스를 구현했다. 하지만 이런 방식은 테스트 코드 구현도 부담인데 매번 새로운 가짜 클래스를 만들어야 하는 부담이 추가되는 격이다. </p>\n<ul>\n<li>이를 위해 <code class=\"language-text\">Mock</code> 클래스 구현 없이도 테스트가 가능하도록 지원하는 <code class=\"language-text\">Mock</code> 테스트 프레임워크를 활용한다.</li>\n</ul>\n<p>먼저 메이븐 설정 파일에 의존관계를 추가한다.</p>\n<deckgo-highlight-code language=\"xml\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">&lt;dependency&gt;\n    &lt;groupId&gt;org.mockito&lt;/groupId&gt;\n    &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;\n    &lt;version&gt;1.10.19&lt;/version&gt;\n    &lt;scope&gt;test&lt;/scope&gt;\n&lt;/dependency&gt;</code>\n        </deckgo-highlight-code>\n<p>이제 이를 활용해 <code class=\"language-text\">QnaService</code> 의 <code class=\"language-text\">deleteQuestion()</code> 메소드에 대한 테스트 코드를 수정한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@RunWith(MockitoJUnitRunner.class)\npublic class QnaServiceTest {\n    @Mock\n    private QuestionDao questionDao;\n    @Mock\n    private AnswerDao answerDao;\n\n    private QnaService qnaService;\n\n    @Before\n    public void setup() {\n        qnaService = new QnaService(questionDao, answerDao);\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void deleteQuestion_없는_질문() throws Exception {\n        when(questionDao.findById(1L)).thenReturn(null);\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n    }\n    ...\n\n    @Test\n    public void deleteQuestion_같은_사용자_답변없음() throws Exception {\n        Question question = newQuestion(1L, &quot;javajigi&quot;);\n        when(questionDao.findById(1L)).thenReturn(question);\n        when(answerDao.findAllByQuestionId(1L)).thenReturn(Lists.newArrayList());\n        qnaService.deleteQuestion(1L, newUser(&quot;javajigi&quot;));\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><code class=\"language-text\">Mock</code> 클래스 없이 테스트를 성공적으로 완료했다.</p>\n<ul>\n<li><strong>Mockito</strong>는 <code class=\"language-text\">Mock</code> 클래스 대신 <code class=\"language-text\">@Mock</code> annotation으로 설정한 클래스의 메소드를 호출했을 때, 반환 값을 지정할 수 있다.</li>\n<li>또한 해당 annotation을 설정한 클래스의 메소드가 호출되는지 여부를 <code class=\"language-text\">verify()</code> 메소드를 통해 검증하는 작업 또한 가능하다.</li>\n<li>이처럼 다른 클래스와 의존관계를 가지는 클래스를 테스트하는 경우 <code class=\"language-text\">Mock</code> 프레임워크의 사용을 추천한다.</li>\n</ul>\n</li>\n</ul>\n<h3>🔧 DI보다 우선하는 객체지향 개발</h3>\n<p>\"계층형 아키텍처 관점과 객체지향 설계 관점에서 핵심적인 비즈니스 로직을 구현해야 하는 역할은 누가 담당해야할까?\"</p>\n<ul>\n<li>먼저 앞에서 구현한 <code class=\"language-text\">DateMessageProvider</code> 코드를 다시 보면서 답에 대해 생각해본다.</li>\n<li>이 코드를 위한 테스트 코드는 다음과 같다. </li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class DateMessageProviderTest {\n    @Test\n    public void 오전() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오전&quot;, provider.getDateMessage(createCurrentDate(11)));\n    }\n\n    @Test\n    public void 오후() throws Exception {\n        DateMessageProvider provider = new DateMessageProvider();\n        assertEquals(&quot;오후&quot;, provider.getDateMessage(createCurrentDate(13)));\n    }\n\n    public Calendar createCurrentDate(int hourOfDay) {\n        Calendar now = Calendar.getInstance();\n        now.set(Calendar.HOUR_OF_DAY, hourOfDay);\n        return now;\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p>이처럼 간단한 로직을 구현하는데 좀 더 간단히 테스트할 수 있는 방법은 없을까에 대해 생각해볼 수 있다.</p>\n<ul>\n<li><code class=\"language-text\">DateMessageProvider</code> 의 구조를 개선해 테스트를 더 쉽게 할 수 없을까?</li>\n<li>좀 더 객체지향적인 개발을 수행한다면 해결책을 얻을 수 있을 것이다.</li>\n</ul>\n</li>\n</ul>\n<p>먼저 시간을 추상화하는 <code class=\"language-text\">Hour</code> 클래스를 추가한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Hour {\n    private int hour;\n\n    public Hour(int hour) {\n        this.hour = hour;\n    }\n\n    public String getMessage() {\n        if (hour &lt; 12) {\n            return &quot;오전&quot;;\n        }\n        return &quot;오후&quot;;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        return false;\n\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        Hour other = (Hour) obj;\n        if (hour != obj.hour) {\n            return false;\n        }\n        return true;\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">Hour</code> 클래스가 <code class=\"language-text\">DateMessageProvider</code> 가 구현하던 로직을 담당하게 되었다. 테스트 코드는 다음과 같다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class MyCalendarTest {\n    @Test\n    public void getHour() throws Exception {\n        Calendar now = Calendar.getInstance();\n        now.set(Calendar.HOUR_OF_DAY, 11);\n        MyCalendar calendar = new MyCalendar(now);\n        assertEquals(new Hour(11), calendar.getHour());\n    }\n}</code>\n        </deckgo-highlight-code>\n<p>위에서 말한 질문에 대한 답변으로, 대부분 Service layer를 담당하고 있는 <code class=\"language-text\">QnaService</code> 에서 처리해야 한다고 생각한다. 하지만 <strong>핵심적인 비즈니스 로직 구현은 Domain 객체가 담당</strong>하는 것이 맞다.</p>\n<ul>\n<li><strong>Service layer</strong>의 핵심 역할은 Domain 객체들이 비즈니스 로직을 구현할 수 있도록 Domain 객체를 조합하거나, 로직 처리 완료 시 상태 값을 DAO를 활용해 DB에 영구 저장하는 등이다.</li>\n</ul>\n<p>대부분의 개발자들은 <code class=\"language-text\">QnaService</code> 의 <code class=\"language-text\">deleteQuestion()</code> 메소드와 같이 구현하는 경우가 많다. 이는 대표적인 <strong>절차지향적 개발</strong>이다. </p>\n<ul>\n<li>이와 같은 개발은 <strong>Service layer의 복잡도는 점점 더 증가</strong>하고</li>\n<li><strong>유지보수와 테스트하기 힘든 상황</strong>을 맞닥뜨리게 된다.</li>\n<li>\n<p>또한 핵심 객체라 할 수 있는 Domain 객체는 사용자가 입력한 데이터를 DAO에 전달하거나 DB 데이터를 뷰에 전달하는 역할만을 수행하게 된다. (핵심적인 역할 수행 X)</p>\n<ul>\n<li>그리하여 Domain 객체가 값을 전달하는 <code class=\"language-text\">Getter</code> &#x26; <code class=\"language-text\">Setter</code> 메소드만을 가지는 상황이 발생한다.</li>\n</ul>\n</li>\n</ul>\n<p>이제부터는 Domain 객체에 더 많은 역할을 부여하는 방향으로 구현하도록 한다.</p>\n<ul>\n<li><code class=\"language-text\">QnaService</code> 의 <code class=\"language-text\">deleteQuestion()</code> 메소드가 구현하고 있는 로직을 Domain 객체, 즉 <code class=\"language-text\">Question</code> &#x26; <code class=\"language-text\">Answer</code> 가 담당하도록 한다.</li>\n<li>먼저, 삭제 가능 여부를 <code class=\"language-text\">Question</code> 에 메세지를 보내(<code class=\"language-text\">canDelete()</code>) 확인하는 방식으로 리팩토링한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Question {\n    ...\n\n    public boolean canDelete(User user, List&lt;Answer&gt; answers) throws CannotDeleteException {\n        if (!user.isSameUser(this.writer)) {\n            throw new CannotDeleteException(&quot;다른 사용자가 작성한 글을 삭제할 수 없습니다.&quot;);\n        }\n        \n        for (Answer answer : answers) {\n            if (!answer.canDelete(user)) {\n                throw new CannotDeleteException(&quot;다른 사용자가 추가한 댓글이 존재해 삭제할 수 없습니다.&quot;);\n            }\n        }\n        \n        return true;\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><code class=\"language-text\">Question</code> 은 인자로 전달된 <code class=\"language-text\">User</code> , <code class=\"language-text\">Answer</code> 와 역할을 나눠 삭제 가능 여부를 판단한다.</p>\n<ul>\n<li><code class=\"language-text\">User</code> 에 질문한 사람의 ID를 전달해 사용자가 동일한지 판단하고,</li>\n<li>글쓴이와 로그인 사용자가 같은 경우 각 답변이 삭제 가능한 상태인지 확인한다. (<code class=\"language-text\">Answer</code>)</li>\n</ul>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class User {\n    ...\n\n    public boolean isSameUser(String newUserId) {\n        return userId.equals(newUserId);\n    }\n}</code>\n        </deckgo-highlight-code>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Answer {\n    ...\n\n    public boolean canDelete(User user) {\n        return user.isSameUser(this.writer);\n    }\n}</code>\n        </deckgo-highlight-code>\n<p>이제 이를 활용해 <code class=\"language-text\">deleteQuestion()</code> 을 수정한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QnaService {\n    ...\n\n    public void deleteQuestion(long questionId, User user) throws CannotDeleteException {\n        Question question = questionDao.findById(questionId);\n        if (question == null) {\n            throw new CannotDeleteException(&quot;존재하지 않는 질문입니다.&quot;);\n        }\n\n        List&lt;Answer&gt; answers = answerDao.findAllByQuestionId(questionId);\n        if (question.canDelete(user, answers)) {\n            questionDao.delete(questionId);\n        }\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>Domain 객체로 로직을 이동시켜 매우 깔끔해졌다. 그렇다고 Domain 객체에 복잡한 로직이 구현된 것은 아니다.</li>\n</ul>\n<blockquote>\n<p>\"객체지향 개발을 하기 위한 좋은 연습은 상태 값을 가지는 Domain 객체에서 값을 꺼내려고 하지 말고 객체에 메세지를 보내 작업을 위임한다는 생각으로부터 시작한다.\"</p>\n</blockquote>\n<p>객체지향적 개발 시 장점 중 하나는 <strong>테스트하기 쉽다</strong>는 것이다. 아래는 <code class=\"language-text\">Question</code> 의 <code class=\"language-text\">canDelete()</code> 메소드에 대한 테스트 코드이다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class QuestionTest {\n    public static Question newQuestion(String writer) {\n        return new Question(1L, writer, &quot;title&quot;, &quot;contents&quot;, new Date(), 0);\n    }\n\n    public static Question newQuestion(long questionId, String writer) {\n        return new Question(questionId, writer, &quot;title&quot;, &quot;contents&quot;, new Date(), 0);\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void canDelete_다른_글쓴이() throws Exception {\n        User user = newUser(&quot;javajigi&quot;);\n        Question question = newQuestion(&quot;sanjigi&quot;);\n        question.canDelete(user, new ArrayList&lt;Answer&gt;());\n    }\n\n    @Test\n    public void canDelete_글쓴이_같음_답변_없음() throws Exception {\n        User user = newUser(&quot;javajigi&quot;);\n        Question question = newQuestion(&quot;javajigi&quot;);\n        assertTrue(question.canDelete(user, new ArrayList&lt;Answer&gt;()));\n    }\n\n    @Test\n    public void canDelete_같은_사용자_답변() throws Exception {\n        User user = newUser(&quot;javajigi&quot;);\n        Question question = newQuestion(&quot;javajigi&quot;);\n        List&lt;Answer&gt; answers = Arrays.asList(newAnswer(&quot;javajigi&quot;), newAnswer(&quot;javajigi&quot;));\n        question.canDelete(user, answers);\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void canDelete_다른_사용자_답변() throws Exception {\n        User user = newUser(&quot;javajigi&quot;);\n        Question question = newQuestion(&quot;javajigi&quot;);\n        List&lt;Answer&gt; answers = Arrays.asList(newAnswer(&quot;javajigi&quot;), newAnswer(&quot;sanjigi&quot;));\n        question.canDelete(user, answers);\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>테스트 코드를 보면, <code class=\"language-text\">QuestionDao</code> , <code class=\"language-text\">AnswerDao</code> 에 대한 의존관계가 없기에 <code class=\"language-text\">Mock</code> 프레임워크를 사용할 필요도 없으며, 구현 또한 간단한 것을 확인할 수 있다.</li>\n</ul>\n<p>이제 <code class=\"language-text\">QnaService</code> 에 대한 테스트를 진행한다면 다음과 같이 할 수 있다. 이미 핵심 비즈니스 로직은 <code class=\"language-text\">QuestionTest</code> 에서 모두 끝낸 상태이다. 즉, <code class=\"language-text\">QnaServiceTest</code> 에서는 <code class=\"language-text\">QnaService</code> 로직에 대해서만 테스트를 수행하면 된다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@RunWith(MockitoJUnitRunner.class)\npublic class QnaServiceTest {\n    @Mock\n    private QuestionDao questionDao;\n    @Mock\n    private AnswerDao answerDao;\n\n    private QnaService qnaService;\n\n    @Before\n    public void setup() {\n        qnaService = new QnaService(questionDao, answerDao);\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void deleteQuestion_없는_질문() throws Exception {\n        when(questionDao.findById(1L)).thenReturn(null);\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n    }\n\n    @Test\n    public void deleteQuestion_삭제할수_있음() throws Exception {\n        User user = newUser(&quot;userId&quot;);\n        Question question = new Question(1L, user.getUserId(), &quot;title&quot;, &quot;contents&quot;, new Date(), 0) {\n            public boolean canDelete(User user, List&lt;Answer&gt; answers) throws CannotDeleteException {\n                return true;\n            };\n        };\n        when(questionDao.findById(1L)).thenReturn(question);\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n        verify(questionDao).delete(question.getQuestionId());\n    }\n\n    @Test(expected = CannotDeleteException.class)\n    public void deleteQuestion_삭제할수_없음() throws Exception {\n        User user = newUser(&quot;userId&quot;);\n        Question question = new Question(1L, user.getUserId(), &quot;title&quot;, &quot;contents&quot;, new Date(), 0) {\n            public boolean canDelete(User user, List&lt;Answer&gt; answers) throws CannotDeleteException {\n                throw new CannotDeleteException(&quot;삭제할 수 없음.&quot;);\n            };\n        };\n        when(questionDao.findById(1L)).thenReturn(question);\n        qnaService.deleteQuestion(1L, newUser(&quot;userId&quot;));\n    }\n}</code>\n        </deckgo-highlight-code>\n<p>관계형 DB를 사용하면서 좀 더 객체지향적인 개발을 위해서는 ORM(Object-Relational Mapping) 프레임워크를 사용할 필요가 있다. 하지만 이를 사용하지 않아도 메소드의 인자로 객체를 전달함으로써 일정 부분 객체지향적인 개발이 가능하다.</p>\n<hr>\n<h2>🚩 DI 프레임워크 실습</h2>\n<h3>🔧 요구사항</h3>\n<p>질문/답변 기능에 DI를 적용하는 작업은 <code class=\"language-text\">LegacyHandlerMapping</code> 에서 구현했다. DI가 필요할 때마다 매번 직접 인스턴스를 생성해 전달하기 귀찮으므로, 자체적인 DI 프레임워크를 구현해본다.</p>\n<p>새로 만든 MVC 프레임워크는 자바 리플렉션을 활용해 <code class=\"language-text\">@Controller</code> annotation이 설정되어 있는 클래스를 찾아 인스턴스를 생성하고, URL 매핑 작업을 자동화했다. 같은 방법으로 각 클래스에 대한 인스턴스 생성 및 의존관계 설정을 자동화한다.</p>\n<ul>\n<li>\n<p>먼저 각 클래스 역할에 맞도록 <code class=\"language-text\">@Controller</code> , <code class=\"language-text\">@Service</code> , <code class=\"language-text\">@Repository</code> annotation을 설정한다.</p>\n<ul>\n<li>3개의 설정으로 생성된 각 인스턴스 간의 의존관계는 <code class=\"language-text\">@Inject</code> annotation을 사용한다.</li>\n</ul>\n</li>\n<li>\n<p>DI 프레임워크로 생성된 인스턴스와 개발자가 <code class=\"language-text\">new</code> 키워드로 생성한 인스턴스를 분리한다.</p>\n<ul>\n<li>DI 프레임워크를 통해 생성된 인스턴스는 <strong>빈(Bean)</strong>이라고 한다.</li>\n</ul>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@Controller\npublic class QnaController extends AbstractController {\n    private MyQnaService qnaService;\n\n    @Inject\n    public QnaController(MyQnaService qnaService) {\n        this.qnaService = qnaService;\n    }\n\n    @RequestMapping(&quot;/questions&quot;)\n    public ModelAndView list(HttpServletRequest req, HttpServletResponse resp) throws Exception {\n        return jspView(&quot;/qna/list.jsp&quot;);\n    }\n}</code>\n        </deckgo-highlight-code>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@Service\npublic class MyQnaService {\n    private UserRepository userRepository;\n    private QuestionRepository questionRepository;\n\n    @Inject\n    public MyQnaService(UserRepository userRepository, QuestionRepository questionRepository) {\n        this.userRepository = userRepository;\n        this.questionRepository = questionRepository;\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@Repository\npublic class JdbcQuestionRepository implements QuestionRepository {\n\n}\n\n@Repository\npublic class JdbcUserRepository implements UserRepository {\n    \n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>제약사항은 빈은 <code class=\"language-text\">@Inject</code> annotation을 가지는 생성자는 하나만 존재하며, 해당 annotation 설정이 되어있지 않으면 인자가 없는 기본 생성자를 제공하는 것으로 한다.</li>\n</ul>\n<h3>🔧 1단계 힌트</h3>\n<p>이 문제 해결을 위해서는 <strong>재귀함수</strong>를 사용해 구현할 수 있다. <code class=\"language-text\">@Inject</code> annotation이 설정된 생성자를 통해 빈을 생성해야 한다.</p>\n<ul>\n<li>그런데 이 생성자의 인자로 전달할 빈도 다른 빈과 의존관계가 있다. 이처럼 빈 간의 의존관계가 연결되어 있을 수 있는데, 이는 다른 빈과 의존관계를 가지지 않는 빈을 찾아 인스턴스를 생성할 때까지 재귀를 실행하는 방식으로 구현할 수 있다.</li>\n</ul>\n<p>재귀를 통해 생성한 빈은 <code class=\"language-text\">BeanFactory</code> 의 <code class=\"language-text\">Map&lt;Class&lt;?>, Object></code> 에 추가해 관리한다. </p>\n<ul>\n<li>인스턴스 생성 전 먼저 <code class=\"language-text\">Class&lt;?></code> 에 해당하는 빈이 <code class=\"language-text\">Map&lt;Class&lt;?>, Object></code> 에 존재 여부를 확인한 후 생성하는 방식으로 구현한다.</li>\n<li><strong>일반적인 캐시의 동작 원리</strong>와 같은 재사용 방법이다.</li>\n</ul>\n<h3>🔧 2단계 힌트</h3>\n<p>빈 인스턴스를 생성하기 위한 재귀 함수 지원을 위해 Class에 대한 빈 인스턴스를 생성하는 메소드와 생성자에 대한 빈 인스턴스를 생성하는 메소드가 필요하다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">private Object instantiateClass(Class&lt;?&gt; clazz) {\n    ...\n    \n    return null;\n}\n\nprivate Object instantiateConstructor(Constructor&lt;?&gt; constructor) {\n    ...\n\n    return null;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>시작은 <code class=\"language-text\">instantiateClass()</code> 이다. </li>\n<li><code class=\"language-text\">@Inject</code> annotation이 설정된 생성자가 존재하면 <code class=\"language-text\">instantiateConstructor()</code> 메소드를 통해 인스턴스를 생성하고, 존재하지 않을 경우 기본 생성자로 인스턴스를 생성한다.</li>\n<li><code class=\"language-text\">instantiateConstructor()</code> 메소드는 생성자의 인자로 전달할 빈이 생성되어 <code class=\"language-text\">Map&lt;Class&lt;?>, Object></code> 에 이미 존재하면 해당 빈을 활용하고, 그렇지 않으면 <code class=\"language-text\">instantiateClass()</code> 을 통해 새로운 빈을 생성한다. </li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">private Object instantiateConstructor(Constructor&lt;?&gt; constructor) {\n    Class&lt;?&gt;[] parameterTypes = constructor.getParameterTypes();\n    List&lt;Object&gt; args = Lists.newArrayList();\n    for (Class&lt;?&gt; clazz : parameterTypes) {\n        ...\n\n        args.add(bean);\n    }\n    return BeanUtils.instantiateClass(constructor, args.toArray());\n}</code>\n        </deckgo-highlight-code>\n<h3>🔧 추가 요구사항 및 힌트</h3>\n<p><code class=\"language-text\">@Controller</code> 가 설정되어 있는 클래스를 찾는 <code class=\"language-text\">ControllerScanner</code> 를 DI 프레임워크가 있는 패키지로 이동해 <code class=\"language-text\">@Controller</code> , <code class=\"language-text\">@Service</code> , <code class=\"language-text\">@Repository</code> 에 대한 지원이 가능하도록 개선한다. 그리고 다른 annotation까지 지원이 가능하게 되므로, <code class=\"language-text\">BeanScanner</code> 로 rename한다.</p>\n<ul>\n<li>또한 <code class=\"language-text\">AnnotationHandlerMapping</code> 이 <code class=\"language-text\">BeanFactory</code> 와 <code class=\"language-text\">BeanScanner</code> 를 활용하도록 리팩토링한다.</li>\n</ul>\n<hr>\n<h2>🚩 DI 프레임워크 구현</h2>\n<p><code class=\"language-text\">BeanFactory</code> 의 <code class=\"language-text\">initialize()</code> 메소드를 구현한다. </p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class BeanFactory {\n    private static final Logger logger = LoggerFactory.getLogger(BeanFactory.class);\n\n    private Set&lt;Class&lt;?&gt;&gt; preInstanticateBeans;\n\n    private Map&lt;Class&lt;?&gt;, Object&gt; beans = Maps.newHashMap();\n\n    public BeanFactory(Set&lt;Class&lt;?&gt;&gt; preInstanticateBeans) {\n        this.preInstanticateBeans = preInstanticateBeans;\n    }\n\n    @SuppressWarnings(&quot;unchecked&quot;)\n    public &lt;T&gt; T getBean(Class&lt;T&gt; requiredType) {\n        return (T) beans.get(requiredType);\n    }\n\n    public void initialize() {\n        for (Class&lt;?&gt; clazz : preInstanticateBeans) {\n            if (beans.get(clazz) == null) {\n                instantiateClass(clazz);\n            }\n        }\n    }\n\n    private Object instantiateClass(Class&lt;?&gt; clazz) {\n        Object bean = beans.get(clazz);\n        if (bean != null) {\n            return bean;\n        }\n\n        Constructor&lt;?&gt; injectedConstructor = BeanFactoryUtils.getInjectedConstructor(clazz);\n        if (injectedConstructor == null) {\n            bean = BeanUtils.instantiate(clazz);\n            beans.put(clazz, bean);\n            return bean;\n        }\n\n        logger.debug(&quot;Constructor : {}&quot;, injectedConstructor);\n        bean = instantiateConstructor(injectedConstructor);\n        beans.put(clazz, bean);\n        return bean;\n    }\n\n    private Object instantiateConstructor(Constructor&lt;?&gt; constructor) {\n        Class&lt;?&gt;[] parameterTypes = constructor.getParameterTypes();\n        List&lt;Object&gt; args = Lists.newArrayList();\n        for (Class&lt;?&gt; clazz : parameterTypes) {\n            Class&lt;?&gt; concreteClazz = BeanFactoryUtils.findConcreteClass(clazz, preInstanticateBeans);\n            if (!preInstanticateBeans.contains(concreteClazz)) {\n                throw new IllegalStateException(clazz + &quot;는 Bean이 아닙니다.&quot;);\n            }\n            Object bean = beans.get(concreteClazz);\n            if (bean == null) {\n                bean = instantiateClass(concreteClazz);\n            }\n            args.add(bean);\n        }\n        return BeanUtils.instantiateClass(constructor, args.toArray());\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">BeanFactory</code> 에서 핵심 구현 로직은 <code class=\"language-text\">instantiateClass()</code> , <code class=\"language-text\">instantiateConstructor()</code> 메소드이다. 이 두 메소드의 재귀호출을 통해 복잡한 의존관계에 있는 빈을 생성하는 과정을 완료할 수 있다.</li>\n</ul>\n<p>이제 <code class=\"language-text\">@Controller</code> , <code class=\"language-text\">@Service</code> , <code class=\"language-text\">@Repository</code> annotation이 설정된 빈을 찾는 <code class=\"language-text\">BeanScanner</code> 를 구현한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class BeanScanner {\n    private Reflections reflections;\n\n    public BeanScanner(Object... basePackage) {\n        reflections = new Reflections(basePackage);\n    }\n    \n    public Set&lt;Class&lt;?&gt;&gt; scan() {\n        return getTypeAnnotatedWith(Controller.class, Service.class, Repository.class);\n    }\n\n    private Set&lt;Class&lt;?&gt;&gt; getTypeAnnotatedWith(Class&lt;? extends Annotation&gt;... annotations) {\n        Set&lt;Class&lt;?&gt;&gt; preInstantiatedBeans = Sets.newHashSet();\n        for (Class&lt;? extends Annotation&gt; annotation : annotations) {\n            preInstantiatedBeans.addAll(reflections.getTypesAnnotatedWith(annotation));\n        }\n        return preInstantiatedBeans;\n    }\n}</code>\n        </deckgo-highlight-code>\n<p>이제 생성한 <code class=\"language-text\">BeanFactory</code> 를 <code class=\"language-text\">AnnotationHandlerMapping</code> 이 사용하도록 리팩토링한다. 먼저 <code class=\"language-text\">@Controller</code> annotation을 설정한 빈을 조회하는 메소드를 추가한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class BeanFactory {\n    ...\n\n    public Map&lt;Class&lt;?&gt;, Object&gt; getControllers() {\n        Map&lt;Class&lt;?&gt;, Object&gt; controllers = Maps.newHashMap();\n        for (Class&lt;?&gt; clazz : preInstanticateBeans) {\n            Annotation annotation = clazz.getAnnotation(Controller.class);\n            if (annotation != null) {\n                controllers.put(clazz, annotation);\n            }\n        }\n        return controllers;\n    }\n}</code>\n        </deckgo-highlight-code>\n<p><code class=\"language-text\">AnnotationHandlerMapping</code> 에서는 <code class=\"language-text\">BeanFactory</code> 를 초기화한 후 <code class=\"language-text\">@Controller</code> 로 설정한 빈을 사용하면 된다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class AnnotationHandlerMapping implements HandlerMapping {\n    private static final Logger logger = LoggerFactory.getLogger(AnnotationHandlerMapping.class);\n\n    private Object[] basePackage;\n\n    private Map&lt;HandlerKey, HandlerExecution&gt; handlerExecutions = Maps.newHashMap();\n\n    public AnnotationHandlerMapping(Object... basePackage) {\n        this.basePackage = basePackage;\n    }\n\n    public void initialize() {\n        BeanScanner beanScanner = new BeanScanner(basePackage);\n        BeanFactory beanFactory = new BeanFactory(beanScanner.scan());\n        beanFactory.initialize();\n        \n        Map&lt;Class&lt;?&gt;, Object&gt; controllers = beanFactory.getControllers();\n        Set&lt;Method&gt; methods = getRequestMappingMethods(controllers.keySet());\n        for (Method method : methods) {\n            RequestMapping rm = method.getAnnotation(RequestMapping.class);\n            logger.debug(&quot;register handlerExecution : url is {}, method is {}&quot;, rm.value(), method);\n            handlerExecutions.put(createHandlerKey(rm),\n                    new HandlerExecution(controllers.get(method.getDeclaringClass()), method));\n        }\n\n        logger.info(&quot;Initialized AnnotationHandlerMapping!&quot;);\n    }\n    ...\n\n}</code>\n        </deckgo-highlight-code>\n<h2>📕 출처</h2>\n<p><strong>자바 웹 프로그래밍 Next Step : 하나씩 벗겨가는 양파껍질 학습법</strong> - 박재성</p>","frontmatter":{"title":"📖 11장 의존관계 주입(DI)을 통한 테스트하기 쉬운 코드 만들기","date":"February 21, 2022","update":"February 21, 2022","tags":["Java","Refactoring","Framework"],"series":"📖 자바 웹 프로그래밍 Next Step"},"fields":{"slug":"/[NextStep]11/","readingTime":{"minutes":32.425}}},"seriesList":{"edges":[{"node":{"id":"f9691a13-3a27-5449-812b-5819a032b5cf","fields":{"slug":"/[NextStep]1/"},"frontmatter":{"title":"📖 1장 첫 번째 양파 껍질 벗기기"}}},{"node":{"id":"0a455dd6-0b0a-5012-adf7-ca17d9590acd","fields":{"slug":"/[NextStep]2/"},"frontmatter":{"title":"📖 2장 문자열 계산기 구현을 통한 테스트와 리팩토링"}}},{"node":{"id":"e95f7d47-9b6c-58c1-a6db-3faa35ba2bfd","fields":{"slug":"/[NextStep]3/"},"frontmatter":{"title":"📖 3장 개발 환경 구축 및 웹 서버 실습 요구사항"}}},{"node":{"id":"f940f29a-3fda-5127-93a7-d4776e581630","fields":{"slug":"/[NextStep]4/"},"frontmatter":{"title":"📖 4장 HTTP 웹 서버 구현을 통해 HTTP 이해하기"}}},{"node":{"id":"e192a3a9-2352-50a1-81fa-c042806ea2a2","fields":{"slug":"/[NextStep]5/"},"frontmatter":{"title":"📖 5장 웹 서버 리팩토링, 서블릿 컨테이너와 서블릿의 관계"}}},{"node":{"id":"9197157a-75bc-5414-8292-da27dd69a4e1","fields":{"slug":"/[NextStep]6/"},"frontmatter":{"title":"📖 6장 서블릿/JSP를 활용해 동적인 웹 애플리케이션 개발하기"}}},{"node":{"id":"4eec34ae-1e1a-5d59-bcd1-ed5f37722bc9","fields":{"slug":"/[NextStep]7/"},"frontmatter":{"title":"📖 7장 DB를 활용해 데이터를 영구적으로 저장하기"}}},{"node":{"id":"b15cc289-ba13-5439-be9b-2ccce07b1516","fields":{"slug":"/[NextStep]8/"},"frontmatter":{"title":"📖 8장 AJAX를 활용해 새로고침 없이 데이터 갱신하기"}}},{"node":{"id":"7c85cb46-2df5-5972-8e38-24208d1e06b5","fields":{"slug":"/[NextStep]9/"},"frontmatter":{"title":"📖 9장 두번째 양파 껍질을 벗기기 위한 중간 점검"}}},{"node":{"id":"43d32ee6-419a-5f7f-a3d5-d720774977fc","fields":{"slug":"/[NextStep]10/"},"frontmatter":{"title":"📖 10장 새로운 MVC 프레임워크 구현을 통한 점진적 개선"}}},{"node":{"id":"168191bb-b6de-5d4d-9d33-b9b8183f3857","fields":{"slug":"/[NextStep]11/"},"frontmatter":{"title":"📖 11장 의존관계 주입(DI)을 통한 테스트하기 쉬운 코드 만들기"}}},{"node":{"id":"361fa9e9-c9e8-568d-8e23-3ccddd10537e","fields":{"slug":"/[NextStep]12/"},"frontmatter":{"title":"📖 12장 확장성 있는 DI 프레임워크로 개선"}}}]},"previous":{"fields":{"slug":"/[BOJ]5014/"},"frontmatter":{"title":"👩‍💻 5014. 스타트 링크"}},"next":{"fields":{"slug":"/[NextStep]12/"},"frontmatter":{"title":"📖 12장 확장성 있는 DI 프레임워크로 개선"}}},"pageContext":{"id":"168191bb-b6de-5d4d-9d33-b9b8183f3857","series":"📖 자바 웹 프로그래밍 Next Step","previousPostId":"b3394e53-5e9a-595e-8da4-bb3debd220c0","nextPostId":"361fa9e9-c9e8-568d-8e23-3ccddd10537e"}},"staticQueryHashes":[]}